//#define DEBUG_SINGLEWINDOW

// Fridge
#include "Controller/Controller_Main.h"
#include "Main.h"
#include "SDL.h"
#include "FileTools.h"
#include "CmdlineParameters.h"
#include "AudioHelper.h"
#include "FridgeScript/FridgeScript.h"
#include "Input.h"
#include "Preset/Preset.h"
#include "SDLEventSystem.h"
#include "SuperTree.h"
#include "TextureManager.h"
#include "TextRender.h"
#include "Timer.h"
#include "Visuals/Visuals_Main.h"

// External
#include <SDL.h>
#include <stdio.h>

#ifdef FRIDGE_QTGUI_ENABLED
#include "FridgeGUI/FridgeGui.h"
#include <QApplication>
#endif

using namespace std;

int main( int argc, char* argv[] )
{
	CONTROLLER_SCREEN eScreen = CONTROLLER_SCREEN_NONE;
	CmdlineParameters::InitCmdlineArgs(argc, argv);
	CmdlineParameters::SetCmdlineScreen(&eScreen);
	
	FridgeLog("Platform Init\n");
	
	Platform::Initialise();
	FridgeLog("SDL_Init\n");
	
	if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
	{
		return 0;
	}
	
	FridgeLog("SDL_Init complete\n");
	
	SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
	SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );
	
	Preset xPreset;
	
	Clipboard::Initialise();
	
	AudioHelper::Initialise();
	
	FridgeScript::Initialise();
	
	TextRender::Initialise();
	
	#ifndef DEBUG_SINGLEWINDOW
	Visuals_Main::Initialise	( &xPreset );
	#endif
	Controller_Main::Initialise ( &xPreset, eScreen);
	SDLEventSystem::Initialise();
	
	#ifdef FRIDGE_QTGUI_ENABLED
	QApplication xGuiApp(argc, argv);
	FridgeGui xGUI;
	xGUI.show();
	#endif
	
	while( !Controller_Main::ShouldQuit() )
	{
		SDLEventSystem::Update();
		Timer::Update();
		AudioHelper::Update();
		
		Controller_Main::Update	();
		
		Controller_Main::Render ();
		#ifndef DEBUG_SINGLEWINDOW
		Visuals_Main::Render	();
		#endif
		
		#ifdef FRIDGE_QTGUI_ENABLED
		xGuiApp.processEvents();
		#endif
	}
	
	FridgeLog("Shutting down\n");
	
	TextRender::Shutdown		();
	Controller_Main::Shutdown	();
    #ifndef DEBUG_SINGLEWINDOW
	Visuals_Main::Shutdown		();
	#endif
	
	FridgeScript::Shutdown();
	
	SDLEventSystem::Shutdown();
	
	AudioHelper::Shutdown();
	
	Clipboard::Shutdown();
	
	FridgeLog("SDL_Quit\n");
	
	SDL_Quit();
	
	FridgeLog("Platform Shutdown\n");
	
	Platform::Shutdown();
	
	return 0;
}
